from fastapi import APIRouter, Form, Header, Depends

from app.api.deps import DbDependency, CurrentUserDependency
from app.core.dependencies import store_sms_code, verify_captcha
from app.core.security import create_access_token
from app.crud import member_service
from app.schemas.member import MemberVo
from app.utils.captcha import generate_random_sms_code
from app.utils.response import success_response, error_response

router = APIRouter()


@router.post("/send", summary="发送短信验证码")
async def send_sms(captchaCode: str = Form(..., description="图形验证码内容"),
                   captchaKey: str = Form(..., description="图形验证码的key"),
                   mobile: str = Form(..., description="手机号码")):
    # 校验验证码
    is_valid = verify_captcha(captchaKey, captchaCode)
    if not is_valid:
        return error_response(status_code=403, message="验证码不正确")
    sms_code = generate_random_sms_code(4)
    store_sms_code(mobile, sms_code)
    return success_response(data=sms_code, message="短信发送成功")


@router.post("/login", summary="短信登录")
async def login(db: DbDependency,
                smsCode: str = Form(..., description="图形验证码内容"),
                isParty: str = Form(None, description="图形验证码的key"),
                mobile: str = Form(..., description="手机号码"),
                partyData: object = Form(None, description="哈哈哈"),
                platform: str = Header(..., description="平台类型")
                ):
    # 校验短信证码
    # is_valid = verify_sms_code(mobile, smsCode)
    # if not is_valid:
    # return error_response(status_code=403, message="验证码不正确")
    member_info = member_service.get_member_by_phone(db=db, phone=mobile)
    if not member_info:
        # 不存在则注册会员信息
        user = member_service.register_member(db, mobile, mobile, platform)
    access_token = create_access_token(member_info.id)
    return success_response(data={
        "userId": member_info.id,
        "token": "Bearer " + access_token
    },
        message="登录成功")


@router.get("/getUserInfo", summary="获取登录人信息")
async def get_user_info(member: MemberVo = Depends(CurrentUserDependency)):
    return member
